#include "file_scanner.h"

void FileScan(const QString& ScanPath, QSharedPointer<MTree> Mroot)
{
    QString searchPath = ScanPath + "\\*";
    WIN32_FIND_DATA ScanFile;
    HANDLE ScanHandle = FindFirstFileW((LPCWSTR)searchPath.utf16(), &ScanFile);
    if (ScanHandle == INVALID_HANDLE_VALUE) { return; }
    do
    {
        QString fileName = QString::fromWCharArray(ScanFile.cFileName);
        QString filePath = ScanPath + "\\" + fileName;
        QDateTime creationTime = fileTimeToQDateTime(ScanFile.ftCreationTime);
        QDateTime lastAccessTime = fileTimeToQDateTime(ScanFile.ftLastAccessTime);
        QDateTime lastWriteTime = fileTimeToQDateTime(ScanFile.ftLastWriteTime);
        if (ScanFile.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { continue; }
        if (!(ScanFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
        {
            qint64 fileSize=(((qint64)ScanFile.nFileSizeHigh) << 32) + ScanFile.nFileSizeLow;
            QFileInfo temp(fileName);
            QString Type = temp.suffix();
            if(Type.isEmpty()) Type="ThisIsEmp";
            FileInfo newFile(fileName, Type, filePath, fileSize, creationTime, lastAccessTime, lastWriteTime);
            Mroot->addChild(newFile);
        }
        else if (fileName != "." && fileName != "..")
        {
            QString DirFilePath=filePath+"\\";
            FileInfo newDir(fileName, "Dir", DirFilePath, creationTime, lastAccessTime, lastWriteTime);
            QSharedPointer<MTree> newMroot=Mroot->addChild(newDir);
            FileScan(filePath, newMroot);
        }
    }
    while (FindNextFileW(ScanHandle, &ScanFile) != 0);
    FindClose(ScanHandle);
}

void MultiScan(QVector<QString> Roots, QSharedPointer<MTree> Mroot)
{
    for(const QString& path:Roots)
    {
        FileInfo newPath(path,path);
        Mroot->addChild(newPath);
        FileScan(path,Mroot->getLastChild());
    }
}

void WindowsScan(QSharedPointer<MTree> Mroot)
{
    QVector<QString> disks=GetLoadedDisks();
    MultiScan(disks,Mroot);
}
